<template>
    <el-card >
        <div class="reset-password">
            <h2>重置密码</h2>
            <el-form @submit.prevent="resetPassword" :model="rePwd" :rules="rules" ref="formRef" label-position="top">
                <el-form-item label="旧密码" prop="oldPassword">
                    <el-input type="password" v-model="rePwd.old_pwd" required></el-input>
                </el-form-item>
                <el-form-item label="新密码" prop="password">
                    <el-input type="password" v-model="rePwd.new_pwd" required></el-input>
                </el-form-item>
                <el-form-item label="确认密码" prop="confirmPassword">
                    <el-input type="password" v-model="rePwd.re_pwd" required></el-input>
                </el-form-item>
                <el-button type="primary" native-type="submit" :loading="loading">重置密码</el-button>
                <p v-if="error" class="error">{{ error }}</p>
                <p v-if="success" class="success">{{ success }}</p>
            </el-form>
        </div>
    </el-card>
</template>

<script setup>
import { ref } from 'vue';
import { ElForm, ElFormItem, ElInput, ElButton, ElMessage } from 'element-plus';

const formRef = ref(null);

const rePwd = ref({
    old_pwd: '',
    new_pwd: '',
    re_pwd: ''
});

import { userPasswordUpdateService } from '@/api/user';
import { useTokenStore } from '@/stores/token'
import router from '@/router';
const resetPassword = async () => {
  try {
    let result = await userPasswordUpdateService(rePwd.value)
    ElMessage.success(result.msg ? result.msg : '重置密码成功,请重新登录')
    let tokenStore = useTokenStore();
    tokenStore.removeToken();
    router.push('/login');
    // 可以在这里添加其他操作，例如跳转页面或刷新用户信息
  } catch (error) {
    ElMessage.error(error.message || '重置密码失败')
  }
}

// 定义 validateConfirmPassword 函数
const validateConfirmPassword = (rule, value, callback) => {
    if (value !== rePwd.value.new_pwd) {
        callback(new Error('两次输入的密码不一致'));
    } else {
        callback();
    }
};

// 定义 rules 对象
const rules = {
    old_pwd: [
        { required: true, message: '请输入旧密码', trigger: 'blur' },
        { min: 6, max: 20, message: '旧密码长度应在6到20个字符之间', trigger: 'blur' }
    ],
    new_pwd: [
        { required: true, message: '请输入新密码', trigger: 'blur' },
        { min: 6, max: 20, message: '新密码长度应在6到20个字符之间', trigger: 'blur' },
    ],
    re_pwd: [
        { required: true, message: '请再次输入新密码', trigger: 'blur' },
        { validator: validateConfirmPassword, trigger: 'blur' }
    ]
};


</script>

<style scoped>
.reset-password {
    max-width: 400px;
    margin: 0 auto;
    padding: 20px;
    border: 1px solid #ccc;
    border-radius: 5px;
}

.error {
    color: red;
    margin-top: 10px;
}

.success {
    color: green;
    margin-top: 10px;
}
</style>